package com.tangtang.basic.threads.demo;

public class VolatileDemo {
    private  volatile  static int flag = 0;

    public static class Thread1 extends Thread {
        @Override
        public void run() {
            while (true) {
                System.out.println("修改前flag为" + flag + ",修改后为" + (++flag));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Thread2 extends Thread {
        @Override
        public void run() {
            int nativeFalg = flag;
            while (true) {
                if (nativeFalg != flag) {
                    System.out.println("修改后为" + flag);
                    nativeFalg = flag;
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();

        Thread2 thread2 = new Thread2();
        thread2.start();

    }
}
